package calibration

import (
	"ewdetect/comms"
	"ewdetect/config"
	"ewdetect/stations"
	"math"
	"time"

	"github.com/rs/zerolog/log"
)

func Init() {
	if !config.FastStartup {
		log.Info().Msg("Collecting data for cold start calibration")
		time.Sleep(config.ColdStartCalibrationTime)
		log.Info().Msg("Starting cold start calibration")
		for connection := range comms.Connections {
			if _, ok := stations.Stations[connection]; ok {
				for key := range *comms.Connections[connection].Buffers {
					log.Debug().
						Str("connection", connection).
						Str("key", key).
						Msg("Processing calibration")
					buffer := *(*comms.Connections[connection].Buffers)[key]
					head := (*comms.Connections[connection].Heads)[key]
					avg := int32(0)
					n := int32(0)
					for i, b := range buffer {
						if i < head {
							avg += b
							n++
						}
					}
					dc := avg / n
					rmss := .0
					for i, b := range buffer {
						if i < head {
							floatS := float64(b - dc)
							rmss += floatS * floatS
						}
					}
					noise_floor := int32(math.Sqrt(2) * math.Sqrt(rmss/float64(n)))
					prev := (*stations.Stations[connection])[key]

					(*stations.Stations[connection])[key] = stations.Station{
						Name:       prev.Name,
						Lat:        prev.Lat,
						Lon:        prev.Lon,
						SampleRate: prev.SampleRate,
						DC:         dc,
						NoiseFloor: noise_floor,
						Calibrated: true,
					}
					log.Debug().
						Str("station", prev.Name).
						Int32("dc", dc).
						Int32("noise_floor", noise_floor).
						Msg("Station calibrated")
				}
			}
		}
		stations.SerializeStationData()
		log.Info().Msg("Calibration complete")
	}
}
